package com.bluetoothsms.android;

import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.bluetoothsms.common.Common;

public class ServerThread extends Thread {
	private final static UUID BT_CONN_UUID = UUID.fromString(Common.UUID);
	private final static String BT_CONN_NAME = "BluetoothSMS";
	private final Handler mHandler;

	private BluetoothServerSocket mServerSocket;
	private BluetoothSocket mSocket;
	private String mErrorMsg = "";

	public ServerThread(BluetoothAdapter blue, Handler handler)
			throws IOException {
		mHandler = handler;

		// MY_UUID is the app's UUID string, also used by the client code
		mServerSocket = blue.listenUsingRfcommWithServiceRecord(BT_CONN_NAME,
				BT_CONN_UUID);

		Log.v(getClass().getSimpleName(), "Listening on socket:"
				+ mServerSocket.toString());
	}

	public void run() {
		mSocket = null;

		if (mServerSocket != null) {
			// Keep listening until exception occurs or a socket is returned
			try {
				Log.v(getClass().getSimpleName(), "Accepting on socket:"
						+ mServerSocket.toString());

				mSocket = mServerSocket.accept();

				Log.v(getClass().getSimpleName(), "Accepted.");

				Message msg = Message.obtain(mHandler, Common.MSG_CONNECTED);
				msg.sendToTarget();
			} catch (IOException e) {
				mErrorMsg = e.getMessage();
				Message msg = Message.obtain(mHandler,
						Common.MSG_CONNECTION_FAILED);
				msg.sendToTarget();
			}

			cancel();

		} else {
			mErrorMsg = "Server Socket is null!";
			Message msg = Message
					.obtain(mHandler, Common.MSG_CONNECTION_FAILED);
			msg.sendToTarget();
		}

		Log.v(getClass().getSimpleName(), "Has quit.");
	}

	public BluetoothSocket getSocket() {
		return mSocket;
	}

	public String getErrorMessage() {
		return mErrorMsg;
	}

	/** Will cancel the listening socket, and cause the thread to finish */
	public synchronized void cancel() {

		if (mServerSocket != null) {
			try {
				Log.v(getClass().getSimpleName(), "Closing server socket:"
						+ mServerSocket.toString());

				mServerSocket.close();
			} catch (IOException e) {
				mErrorMsg = e.getMessage();
			}

			mServerSocket = null;
		}
	}
}
